import logging
import os
import string
import sys

import util.common

import method

log = logging.getLogger('config')

#----------------------------------------------------------------------------
class Config:
    """Holds the configuration information for this instance of neon."""

    def __init__(self):
        self.parse_config()

    def parse_config(self):
        """Parse configuration from the command line and the
        environmental variables"""
        if '--help' in sys.argv or '-h' in sys.argv:
            self.print_usage()
            sys.exit(0)

        # format = '%(asctime)s %(levelname)-8s %(message)s'
        format = '%(name)-8s %(levelname)-8s | %(message)s'
        if '--debug' in sys.argv:
            logging.basicConfig(level=logging.DEBUG, format=format)
        else:
            logging.basicConfig(level=logging.INFO, format=format)

        util.common.use_dtest = '--dtest' in sys.argv

        id   = 'unassigned_id'
        addr = 'localhost'
        port = '6000'
    
        for i in sys.argv:
            o = i.split('=')
            if o[0] == '--addr':
                neon_addr, neon_port = o[1].split(':')
            elif o[0] == '--id':
                id = o[1]

        self.transports = {}
        for k in os.environ.keys():
            if k == 'TX_ID':
                id = os.environ[k]
            elif k == 'TX_ADDR':
		if ':' in os.environ[k]:
                    addr, port = os.environ[k].split(':')
                else:
                    # use UNIX domain socket
                    addr = os.environ[k]
                    port = 0
            elif k[:len('TX_TRANSPORT_')] == 'TX_TRANSPORT_':
                transport_id = k[len('TX_TRANSPORT_'):]
                self.transports[transport_id] = os.environ[k].split(',')
            elif k == 'TX_DTEST':
                util.common.use_dtest = True
                
        self.id = id
        self.ap = (addr, int(port))

        log.debug('--- CONFIGURATION ---\n%s' %
                  string.join(['    ' + e + ': ' + str(getattr(self, e))
                               for e in dir(self) if e[:2] != '__'], '\n'))

    def print_usage(self):
        print """tx.py [opts...]
        
Transport connection management daemon.

  options:
    --debug

    Enable debug output.

    --addr=<addr>:<port>|<sock filename>|stdin

    default = localhost:6000

    Address and port for the API service port. If filename is specified,
    then a UNIX domain socket will be used. If 'stdin' is specified, then
    stdin will be used.
    
    --id=<id>      default = unassigned_id

    Id string for this node.

  environmental variables:

    TX_ID

        Id of the neon instance.

    TX_ADDR

        Address and port for the API service port. If filename is
        specified, then a UNIX domain socket will be used. If 'stdin'
        is specified, then stdin will be used.

    TX_TRANSPORT_/id/

	List of comma separated transport method configuration.
        """
        print """Transport methods:
        """
        for k in method.method_descriptions.keys():
            print method.method_descriptions[k]
